#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
=================================================
# @File    : larkdriver
# @IDE     : PyCharm
# @Author  : liuxiangui
# @Date    : 2023/11/4 14:56
# @Describe: 
==================================================
'''
import time
import json
import urllib3
import requests
from library.log import logger
urllib3.disable_warnings()

class LarkChatBot:
    """飞书机器人通知"""
    def __init__(self, hook_link, report_link='', project_name=''):
        self.reportLink = report_link
        self.projecName=project_name
        self.hookLink = hook_link
    def post(self,data):
        """
        发送消息（内容UTF-8编码）
        :return: 返回消息发送结果
        """

        richText = {
            "msg_type": "interactive",
            "card": {
                "elements": [
                    {
                        "tag": "div",
                        "text":
                        {
                            "content": f"{data}",
                            "tag":"lark_md"
                        }
                    },
                    {
                        "actions": [
                            {
                                "tag": "button",
                                "text":
                                {
                                    "content": "测试报告:白眼:",
                                    "tag":"lark_md"
                                },
                                "url": self.reportLink,
                                "type": "default",
                                "value": {}
                            }
                        ],
                        "tag": "action"
                    }
                ],
                "header": {
                    "title":{
                        "content": f"【{self.projecName}】接口自动化报告",
                        "tag": "plain_text"
                    }
                }
            }
        }
        headers = {'Content-Type': 'application/json; charset=utf-8'}
        postData = json.dumps(richText)
        response = requests.post(
                self.hookLink,
                headers=headers,
                data=postData,
                verify=False
        )
        result = response.json()
        logger.info(f"飞书机器人通知成功！{response.json()}")
        if result.get('StatusCode') != 0:
            timeNow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
            resultMsg = result['errmsg'] if result.get('errmsg', False) else '未知异常'
            errorData = {
                "msgtype": "text",
                "text": {
                            "content": f"[注意-自动通知]飞书机器人消息发送失败，时间：{timeNow}，"
                                       f"原因：{resultMsg}，请及时跟进，谢谢!"
                },
                "at": {
                            "isAtAll": False
                        }
                    }
            logger.error("消息发送失败，自动通知：%s", errorData)
            requests.post(self.hookLink, headers=headers, data=json.dumps(errorData))
        return result
if __name__ == '__main__':
    one = LarkChatBot()
    one.post("id,casename,header,body,predict,result\n1,xiaomng,A,2,w,1\n1,xiaohua,B,2,w,1\n2,xiaomng,Q,2,q,1\n2,xiaohua,A,3,q,0")